﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TDT.Land.Entity;
using TDT.Land.Utilities;
using TDT.Land.BusinessLogic;
using TDT.Land.Models;
using System.Web.Routing;

namespace TDT.Land.Web.Controllers
{
    public class AdminController : BaseController
    {
        //
        // GET: /Admin/
        //[Extent.CustomAuthorize(Roles = UserType.E_ADMIN + "|"+ UserType.E_ADMIN_ROOT)]
        [CustomAuthorize(Roles = "2")]
        public ActionResult Index()
        {
            ViewBag.docBody = "nguyend duy";
//<table border='0' cellpadding='4' cellspacing='4'> <tbody> <tr> <td> <p> <img src='/Uploads/j0262681.jpg' alt='' height='53' width='80' /></p></td> <td> <p>When your algorithmic and programming skills have reached a level which you cannot improve any further, refining your team strategy will give you that extra edge you need to reach the top. We practiced programming contests with different team members and strategies for many years, and saw a lot of other teams do so too. </p></td></tr> <tr> <td> <p> <img src='/Uploads/PH02366J.jpg' alt='' height='52' width='80' /></p></td> <td> <p>From this we developed a theory about how an optimal team should behave during a contest. However, a refined strategy is not a must: The World Champions of 1995, Freiburg University, were a rookie team, and the winners of the 1994 Northwestern European Contest, Warsaw University, met only two weeks before that contest. </p></td></tr></tbody></table> ";
            return View();
        }

        #region Kiểm Tra Quyền view
        public JsonResult CheckPermission(string pageName)
        {
            var isAllowed= SecurityRepo.Instance.CheckPermission(Guid.Parse("F53DB0BA-B6AF-42BA-9322-2E9253C2262F")
                , Helper.Security.PrivilegeType.Create, pageName);

            return Json(isAllowed, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region Login
        public ActionResult LoginView()
        {
            return View();
        }
        [HttpPost]
        public JsonResult LoginAction(LogOnModel model)
        {
            bool status = false;
            string msg = string.Empty;
            if (model == null || model.UserName == null || model.Password == null || model.UserName.Trim() == string.Empty || model.Password.Trim() == string.Empty)
            {
                status = false;
                msg = Messages.PlsInputInfomationLogon.Translate();
            }
            else
            {
                Sys_User loginValid = (new AdminRepo()).Login(model.UserName, model.Password);

                if (loginValid!= null)
                {
                    UserNameFull = loginValid.UserName;
                    UserName = loginValid.LoginName;
                    UserID = loginValid.ID;
                    UserTypeSess = loginValid.UserType;
                    UserPermission = loginValid.IsLevel ?? 0;

                    status = true;
                    msg = string.Empty;
                }
                else
                {
                    status = false;
                    msg = Messages.WrongUsernameAndPassword.Translate();
                }
            }

            return Json(new
            {
                Result = status,
                Msg = msg
            });
        }
        public ActionResult LogoutAction()
        {
            //(new AdminRepo()).Logout();
            UserNameFull = string.Empty;
            UserName = string.Empty;
            UserID = Guid.Empty;
            UserTypeSess = string.Empty;
            UserPermission = 0;
            return RedirectToAction("LoginView");

        }
        #endregion

        #region User

        [CustomAuthorize(Roles = "3")]
        public ActionResult openEdit(string id)
        {            
            Guid userId = id!= string.Empty ? Guid.Parse(id): Guid.Empty;

            Sys_User userInfo = AdminRepo.Instance.GetUser(userId);            
            int islevel = userInfo != null ?(int)userInfo.IsLevel : 1;

            ViewBag.select_GroupLevel = GetGroupLevels(islevel);

            return PartialView("User_Edit", userInfo);
        }

        [CustomAuthorize(Roles = "2")]
        public ActionResult User_List()
        {

            List<Sys_User> lstUser = AdminRepo.Instance.GetUsers(UserPermission);
            ViewBag.lstUser = lstUser;

            int itemCount = AdminRepo.Instance.GetCountItemUser();
            int totalPage = itemCount / 20;
            if ((itemCount % 2) > 0)
                totalPage++;

            ViewBag.CountItem = totalPage.ToString();
            

            return View();
        }

        [CustomAuthorize(Roles = "2")]
        public ActionResult GetUser(int NumPage,int NumRow)
        {

            List<Sys_User> lstUser = AdminRepo.Instance.GetUsers(NumPage, NumRow, UserPermission);
            return PartialView("UC_User_List", lstUser);   
        }

        [CustomAuthorize(Roles = "2")]
        public ActionResult UserAction(Sys_User model)
        {
            string str_result = "00";
            if (model.ID == null || model.ID == Guid.Empty) // Tạo mới
            {
                bool CheckUserName = AdminRepo.Instance.CheckUserName(model.LoginName);
                if (!CheckUserName)
                {
                    model.ID = Guid.NewGuid();
                    model.DateChangePass = DateTime.Today.Date;
                    model.UserType = UserType.E_ADMIN;
                    bool result_save = AdminRepo.Instance.CreateUser(model, UserName);
                    if (result_save)
                        str_result = "01"; //save thanh công
                }
                else
                    str_result = "02";// login name đa ton tai

            }
            else //Chinh sua
            {
                bool result_save = AdminRepo.Instance.UpdateUser(model, UserName);
                if (result_save)
                    str_result = "01"; //save thanh công
            }
            return Content(str_result);
        }

        [CustomAuthorize(Roles = "3")]
        public ActionResult UserDelete(string id)
        {
            string saveTT = "00";
            bool result = false;
            if (!string.IsNullOrEmpty(id)) // Delete
            {
                Guid userId = new Guid(id);
                result = AdminRepo.Instance.DeleteUser(userId, UserName); 
                if (result)
                    saveTT = "01";
            }


            return Content(saveTT);
        }

        [CustomAuthorize(Roles = "1")]
        public ActionResult DoChangePass(string passOld, string passNew)
        {
            string _statusUpdate = "00";
            //change user pass

            Sys_User _userCurrent = AdminRepo.Instance.Login(UserName, passOld);
            if (_userCurrent != null)
            {
                _userCurrent.Password = passNew;
                _userCurrent.DateChangePass = DateTime.Now;
                _userCurrent.UserUpdate = UserNameFull;
                bool status = AdminRepo.Instance.UpdateUser(_userCurrent, UserName);
                if (status)
                    _statusUpdate = "01";

            }
            else
                _statusUpdate = "02"; // password không đúng

            return Content(_statusUpdate);
        }

        public ActionResult UserChangePass()
        {
            return PartialView("UC_UserChangePass");
        }


        #endregion

        #region Cat_Land
        public ActionResult CatLandList()
        {
            var catLands = AdminRepo.Instance.GetCatLands();
            return PartialView(ScreenName._CatLandList, catLands);
        }
        #endregion

    }
}
